package com.stockz.indicator.stochastics;

import java.util.List;

import com.stockz.core.model.Bar;
import com.stockz.core.util.BarUtil;
import com.stockz.core.util.BarUtil.BarValueType;
import com.stockz.core.util.ListUtil;
import com.stockz.indicator.Indicator;
import com.stockz.ui.swing.charting.util.MathUtil;

public class StochasticsIndicator implements Indicator<StochasticsIndicatorConfiguration> {

	private StochasticsIndicatorConfiguration stochasticsIndicatorConfiguration
	= new StochasticsIndicatorConfiguration();
	private BarValueType barValueType = BarValueType.AVGPRICE;
	
	@Override
	public double getValue(List<Bar> barList) {
		if(barList == null || barList.size() <= stochasticsIndicatorConfiguration.getSpan()){
			return 0;
		}
		
		double[] values = ListUtil.convert(barList, getBarValueType(), 
				stochasticsIndicatorConfiguration.getSpan());
		double max = MathUtil.max(values, 0, stochasticsIndicatorConfiguration.getSpan());
		double min = MathUtil.min(values, 0, stochasticsIndicatorConfiguration.getSpan());
		if(max == min){
			return 0;
		}else{
			return ((BarUtil.getValue(barList.get(0),getBarValueType())-min)*100)/(max-min);
		}
	}

	@Override
	public double[] getValues(List<Bar> barList) {
		if(barList == null || barList.size() < stochasticsIndicatorConfiguration.getSpan()){
			return new double[0];
		}
		double[] values = new double[barList.size()];
		for(int i = barList.size()-1; i >=0; i--){
			if(i >= barList.size() - stochasticsIndicatorConfiguration.getSpan()-1){
				values[i] = 0;
			}else{
				values[i] = getValue(barList.subList(i, i+stochasticsIndicatorConfiguration.getSpan()+1));
			}
		}
		return values;
	}
	
	@Override
	public StochasticsIndicatorConfiguration getIndicatorConfiguration() {
		return stochasticsIndicatorConfiguration;
	}

	public BarValueType getBarValueType() {
		return barValueType;
	}

	public void setBarValueType(BarValueType barValueType) {
		this.barValueType = barValueType;
	}

}
